package com.ctrl.riveradministrator.mvp.view.activity.trace;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.TitleOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.trace.model.SortType;
import com.ctrl.riveradministrator.R;
import com.ctrl.riveradministrator.base.BaseActivity;
import com.ctrl.riveradministrator.RaApplication;
import com.ctrl.riveradministrator.common.Constants;
import com.ctrl.riveradministrator.db.SQLiteUtils;
import com.ctrl.riveradministrator.mvp.model.CurrentLocation;
import com.ctrl.riveradministrator.mvp.model.Reach;
import com.ctrl.riveradministrator.mvp.model.Task;
import com.ctrl.riveradministrator.mvp.model.TraceSearch;
import com.ctrl.riveradministrator.mvp.presenter.TracePresenter;
import com.ctrl.riveradministrator.mvp.view.activity.problem_report.ReportActivity;
import com.ctrl.riveradministrator.mvp.view.weight.BottomDialog;
import com.ctrl.riveradministrator.util.BitmapUtil;
import com.ctrl.riveradministrator.util.CommonUtil;
import com.ctrl.riveradministrator.util.MapUtil;
import com.ctrl.riveradministrator.util.TimeUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.ctrl.riveradministrator.RaApplication.getUserId;

public class TraceActivity extends BaseActivity<TracePresenter> implements BaiduMap.OnMarkerClickListener
        , TraceView, BottomDialog.BottomListItemOnClickListener {

    private Toolbar toolbar;
    private TextView titleTv, issueTv, endTv, personTv, stateTv;
    private ImageView leftMenu, rightMenu;
    private LinearLayout endLl;
    private RelativeLayout starLl;
    private ConstraintLayout traceCl, searchCl;
    private RecyclerView list;
    private MapView mapView;
    private BaiduMap map;
    private CardView card;
    private static MapUtil mapUtil;

    private PolygonOptions options;
    private static List<LatLng> listLatLng;
    private List<OverlayOptions> listOverlayOptions;

    private static SQLiteUtils sqLiteUtils;
    private static List<LatLng> points = new ArrayList<LatLng>();
    private static SharedPreferences sp;
    private static SharedPreferences.Editor editor;

    private ProgressDialog progressDialog;
    private BottomDialog bottomDialog;
    private static String[] locs = {"0", "0", "未定位"}; // Baidu地图中传递监听位置数据，locs[0]纬度、locs[1]经度、locs[2]详细地址
    private boolean allSuccess = true;//是否全部上传成功
    private int progressIndex = 0;

    private LocationClient locationClient;
    private LocationListener locationListener;

    List<Reach> reaches = new ArrayList<>();
    List<String> reachNames = new ArrayList<>();
    private MyLocationConfiguration.LocationMode mCurrentMode;

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
        if (!locationClient.isStarted()) {
            locationClient.start();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (locationClient != null)
            locationClient.stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    protected void initParams(Bundle parms) {

    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_trace;
    }

    @Override
    protected TracePresenter createPresenter() {
        return new TracePresenter(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initView(View view) {
        getWindow().getDecorView()
                .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        toolbar = $(R.id.toolbar);
        titleTv = $(R.id.title_tv);
        endLl = $(R.id.end);
        rightMenu = $(R.id.right_iv);
        issueTv = $(R.id.issue_up_tv);
        endTv = $(R.id.end_tv);
        starLl = $(R.id.start);
        leftMenu = $(R.id.left_iv);
        mapView = $(R.id.map);
        personTv = $(R.id.person);
        stateTv = $(R.id.state);
        traceCl = $(R.id.trace);
        searchCl = $(R.id.search);
        list = $(R.id.list);
        card = $(R.id.card);
        map = mapView.getMap();

        /*
         * 设置toolbar
         * */
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setTitle("");
        titleTv.setText(getResources().getString(R.string.river_patrol));
        leftMenu.setBackground(getDrawable(R.drawable.ic_chevron_left_24dp));
        rightMenu.setBackground(getDrawable(R.drawable.ic_baseline_cancel_24));
        setSupportActionBar(toolbar);
        bottomDialog = new BottomDialog(this, reachNames);
    }

    @Override
    protected void doBusiness(Context mContext) {

        try {
            if (Objects.requireNonNull(getIntent().getAction()).equals("task")) {
                card.setVisibility(View.VISIBLE);
                searchCl.setVisibility(View.GONE);
                titleTv.setText(getResources().getString(R.string.river_patrol));
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//使屏幕常亮
            } else {
                card.setVisibility(View.GONE);
                searchCl.setVisibility(View.VISIBLE);
                titleTv.setText(getResources().getString(R.string.trace_select));
            }
            personTv.setText(RaApplication.sp.getString(Constants.USER_ROLE, "未知人员"));
            //---------------------打开悬浮窗权限界面
//            requireFloatViewPermission();
            requireLocPermission();
            //---------------------初始化数据库
            sqLiteUtils = SQLiteUtils.getInstance();
            //---------------------上传进度条
            progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("巡检上传");
            progressDialog.setMessage("当前上传进度");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            //---------------------初始化shared preferences
            sp = getSharedPreferences(Constants.TRACE_SP, MODE_PRIVATE);
            editor = sp.edit();
            //---------------------初始化地图---------------------
            map.setMyLocationEnabled(true);
//            MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(3.0f);
//            map.setMapStatus(msu);
            //设置百度地图最大最小缩放级别  目前百度地图的缩放级别为（3-18）
            map.setMaxAndMinZoomLevel(17, 4);
            initLocation();
            listOverlayOptions = new ArrayList<>();
            options = new PolygonOptions();
            listLatLng = new ArrayList<>();
            points.clear();
            mapUtil = MapUtil.getInstance();
            BitmapUtil.init();
            mapUtil.init(mapView, this);
            mapUtil.setCenter();
            // TODO: 2019/5/21 是否在此进行位置初始化？
            Log.i("cyc", "doBusiness-------------" + sp.getBoolean(Constants.IS_TRACE, false));
            if (sp.getBoolean(Constants.IS_TRACE, false)) {
                endLl.setVisibility(View.VISIBLE);
                starLl.setVisibility(View.GONE);
                stateTv.setText("正在巡检");
                if (CommonUtil.isServiceWork(this, TraceService.class.getSimpleName())) {
                    Log.i("cyc", "服务正在运行..........");
                }
            } else {
                endLl.setVisibility(View.GONE);
                starLl.setVisibility(View.VISIBLE);
            }
            //---------------------拉取初始数据(巡河轨迹)---------------------
            if (!Objects.requireNonNull(getIntent().getAction()).equals("task")) {
                mPresenter.trace(getIntent().getStringExtra("patrolId"));
            }
            //---------------------同步巡检状态---------------------
            mPresenter.isTrace(getUserId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initLocation() {
        setNormalType();
        LocationClient.setAgreePrivacy(true);
        try {
            locationClient = new LocationClient(getApplicationContext());
            locationListener = new LocationListener();
            locationClient.registerLocationListener(locationListener);
            LocationClientOption option = new LocationClientOption();
            option.setCoorType("bd09ll");
            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
            option.setIsNeedAddress(true);
            option.setOpenGps(true);
            option.setLocationNotify(true);
            option.setOpenAutoNotifyMode();
//        option.setOpenAutoNotifyMode(6 * 1000, 30, LocationClientOption.LOC_SENSITIVITY_HIGHT);
            //option.setScanSpan(5000);
            locationClient.setLocOption(option);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        setMyLocation(37.342431, 116.584161);
    }

    /**
     * 设置普通模式
     */
    public void setNormalType() {
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        // 传入null，则为默认图标
        map.setMyLocationConfiguration(new MyLocationConfiguration(mCurrentMode, true, null));
        MapStatus.Builder builder1 = new MapStatus.Builder();
        builder1.overlook(0);
        map.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder1.build()));
    }

    /**
     * 设置跟随模式
     */
    public void setFollowType() {
        mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;
        map.setMyLocationConfiguration(new MyLocationConfiguration(mCurrentMode, true, null));
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.overlook(0);
        map.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }


    /**
     * 设置当前位置
     *
     * @param latitude
     * @param longitude
     */
    private void setMyLocation(double latitude, double longitude) {
        LatLng latLng = new LatLng(latitude, longitude);
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
        map.setMapStatus(msu);
    }

    @Override
    protected void setListener() {
        leftMenu.setOnClickListener(this);
        rightMenu.setOnClickListener(this);
        map.setOnMarkerClickListener(this);
        starLl.setOnClickListener(this);
        issueTv.setOnClickListener(this);
        endTv.setOnClickListener(this);
        bottomDialog.setListItemOnClickListener(this);
    }

    @Override
    protected void widgetClick(View view) {
        switch (view.getId()) {
            case R.id.right_iv:
                AlertDialog.Builder normalDialog =
                        new AlertDialog.Builder(this);
                normalDialog.setTitle("强制结束");
                normalDialog.setMessage("本次巡检数据异常，是否强制结束？点击确认后会清空本次巡检记录。");
                normalDialog.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                sqLiteUtils.deleteAllContact();//清除数据库缓存
                                //情况服务器数据
                                mPresenter.focusEnd(getUserId());
                                stateTv.setText("无巡检任务");
                                endLl.setVisibility(View.GONE);
                                starLl.setVisibility(View.VISIBLE);
                            }
                        });
                normalDialog.setNegativeButton("关闭",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                // 显示
                normalDialog.show();
                break;
            case R.id.left_iv:
                finish();
                break;
            case R.id.start:
                bottomDialog.showReachDialog();
                mPresenter.getReach();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        List<CurrentLocation> currentLocations = sqLiteUtils.queryAll();
                        for (int i = 0; i < currentLocations.size(); i++) {
                            Log.d("cyc", "开始巡河::" + currentLocations.get(i));
                        }
                    }
                }).start();
                break;
            case R.id.end_tv:
                // 由于数据量过大，采用分块上传。如果数据量小于等于200，则直接上传；如果大于200采用以200为差值进行分块查询数据库并上传
                Toast.makeText(this, "正在尝试上传", Toast.LENGTH_SHORT).show();
                int sum = getPointSum();
                if (sum <= 200) {
                    new Thread(() -> {
                        uploadPatrol(0);
                        //完成所有上传后，结束巡检业务
                        handler.sendEmptyMessage(0x09);
                    }).start();
                } else {
                    int black = sum / 200 + 1;
                    progressDialog.setMax(black);
                    progressDialog.show();
                    new Thread(() -> {
                        for (int i = 0; i < black; i++) {
                            uploadPatrol(i);
                        }
                        //完成所有上传后，结束巡检业务
                        handler.sendEmptyMessage(0x09);
                    }).start();
                }
                Log.i("cyc", "结束服务---TraceService---");
                if (points != null)
                    points.clear();
                stopService(new Intent(this, TraceService.class));
                break;
            case R.id.issue_up_tv:
                startActivity(ReportActivity.class);
                break;
            default:
                break;
        }
    }

    /**
     * 开始巡河
     *
     * @param item
     */
    @Override
    public void bottomListDiaItem(String item) {
        for (Reach reach : reaches) {
            if (reach != null && reach.getReservoirName() != null && reach.getReservoirName().equals(item) && reach.getR_flag() == 1) {
                Log.i("cyc", "id == " + reach.getId() + "   getReservoirName == " + reach.getReservoirName());
                mPresenter.startPatrol(getUserId(), reach.getId(), reach.getReservoirName(), "RESERVOIR");
                bottomDialog.cancel();
                return;
            }

            if (reach != null && reach.getReachName() != null && reach.getReachName().equals(item)) {
                Log.i("cyc", "id == " + reach.getId() + "   ReachName == " + reach.getReachName());
                mPresenter.startPatrol(getUserId(), reach.getId(), reach.getReachName(), "REACH");
                bottomDialog.cancel();
            }
        }
    }

    @Override
    public void handleMessage(Message message, int what) {
        switch (message.what) {
            case 0x09:
                if (allSuccess) {
                    //上报成功
                    editor.putBoolean(Constants.IS_TRACE, false);
                    editor.putString(Constants.TRACE_STATE, "无巡检任务");
                    sqLiteUtils.deleteAllContact();//清除数据库缓存
                    editor.apply();
                    progressDialog.cancel();
                    Toast.makeText(this, "巡河上传成功", Toast.LENGTH_SHORT).show();
                    stateTv.setText("无巡检任务");
                    endLl.setVisibility(View.GONE);
                    starLl.setVisibility(View.VISIBLE);
                } else {
                    Toast.makeText(this, "巡河上传失败，请重试", Toast.LENGTH_SHORT).show();
                    progressDialog.cancel();
                }
                //所有标记位回到正常状态
                allSuccess = true;
                progressIndex = 0;
                break;
            case 0x08:
                //更新dialog
                progressIndex = progressIndex + 1;
                progressDialog.setProgress(progressIndex);
                break;
            case 0x07:
                //上报失败
                Toast.makeText(this, "网络故障，上传失败", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    /**
     * 获取数据库点位总数
     *
     * @return
     */
    private int getPointSum() {
        List<CurrentLocation> currentLocations = sqLiteUtils.queryAll();
        return currentLocations.size();
    }

    @SuppressLint("CheckResult")
    private void uploadPatrol(int index) {
        try {
            //List<CurrentLocation> currentLocations = sqLiteUtils.queryAll();
            List<CurrentLocation> currentLocations = sqLiteUtils.queryBlack(index);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId", getUserId());
            jsonObject.put("taskId", sp.getString(Constants.TRACE_TASK_ID, "-1"));
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < currentLocations.size(); i++) {
                Log.d("qqq:", "qqq::" + currentLocations.get(i));
                JSONObject object = new JSONObject();
                object.put("time", currentLocations.get(i).getCreateTime());
                object.put("longitude", currentLocations.get(i).getLongitude());
                object.put("latitude", currentLocations.get(i).getLatitude());
                jsonArray.put(object);
            }
            jsonObject.put("points", jsonArray);
            Log.d("uploadPatrol", ":" + jsonArray.toString());
            mPresenter.upload(jsonObject.toString(), getUserId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class TraceHandler extends android.os.Handler {

        private PolylineOptions mOverlayOptions;

        public TraceHandler() {
            mOverlayOptions = new PolylineOptions();
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x19:
                    try {
                        String[] s = (String[]) msg.obj;
                        locs[0] = s[0];
                        locs[1] = s[1];
                        locs[2] = s[2];
                        sqLiteUtils.addContacts(new CurrentLocation(null,
                                TimeUtil.stampToDate(String.valueOf(System.currentTimeMillis())),
                                s[0], s[1]));
                        Log.d("cyc", "handleMessage ===> latitude:" + s[0] + "longitude:" +
                                s[1] + "create_time:" + TimeUtil.stampToDate(String.valueOf(System.currentTimeMillis())));
                        LatLng point = new LatLng(Double.valueOf(s[0]), Double.valueOf(s[1]));
                        points.add(point);
                        mapUtil.drawHistoryTrack(points, SortType.asc);
                       /* points.add(point);
                        mOverlayOptions.points(points).width(10).color(0xAAFF0000);
                        map.addOverlay(mOverlayOptions);*/
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private class LocationListener extends BDAbstractLocationListener {

        @Override
        public void onLocDiagnosticMessage(int i, int i1, String s) {
            super.onLocDiagnosticMessage(i, i1, s);
            Log.d("activity", "i:" + i + ",+i1:" + i1 + ",s:" + s);
        }

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            //mapView 销毁后不在处理新接收的位置
            if (bdLocation == null || mapView == null) {
                return;
            }

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(bdLocation.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(bdLocation.getDirection()).latitude(bdLocation.getLatitude())
                    .longitude(bdLocation.getLongitude()).build();
            map.setMyLocationData(locData);

            Log.i("cyc", "LocationListener ===>  latitude:" + bdLocation.getLatitude() +
                    "longitude:" + bdLocation.getLongitude() + "code:" + bdLocation.getLocType());
        }
    }

    /**
     * 百度地图绘制线
     *
     * @param mapView
     * @param lists
     */
    public static List<OverlayOptions> addOverlayPath(@NonNull MapView mapView, @NonNull List<TraceSearch> lists) {
        Log.i("cyc", "百度地图绘制线--------------");
        List<OverlayOptions> overlayOptionsList = new ArrayList<>();
        List<LatLng> list = new ArrayList<>();
        for (int i = 0; i < lists.size(); i++) {

            TraceSearch lat2Lng = lists.get(i);
            LatLng p1 = new LatLng(Double.valueOf(lat2Lng.getPatrolLatitude()), Double.valueOf(lat2Lng.getPatrolLongitude()));
            list.add(p1);
        }
        int color = 0xAA477fff;
        OverlayOptions ooPolyline = new PolylineOptions().color(Color.RED).points(list);

        overlayOptionsList.add(ooPolyline);
        return overlayOptionsList;

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x01) {
            if (Build.VERSION.SDK_INT >= 23) {
                if (!Settings.canDrawOverlays(this)) {
                    Toast.makeText(TraceActivity.this, "权限授予失败，请在设置中手动授权", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(TraceActivity.this, "权限授予成功！", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x02) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //用户允许改权限，0表示允许，-1表示拒绝 PERMISSION_GRANTED = 0， PERMISSION_DENIED = -1
                //permission was granted, yay! Do the contacts-related task you need to do.
                //这里进行授权被允许的处理
            } else {
                //permission denied, boo! Disable the functionality that depends on this permission.
                //这里进行权限被拒绝的处理
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    @Override
    public boolean onMarkerClick(Marker marker) {
        Log.i(TAG, "onMarkerClick: " + marker);
        if (marker != null) {
            Bundle bundle = marker.getExtraInfo();
            if (bundle != null) {
                String stationName = bundle.getString("stationName");
                double longitude = bundle.getDouble("longitude");
                double latitude = bundle.getDouble("latitude");
                LatLng point = new LatLng(latitude, longitude);

                Button button = new Button(getApplicationContext());
                button.setBackgroundColor(ContextCompat.getColor(this, R.color.ToolbarBgColor));
                button.setText(stationName);
                InfoWindow infoWindow = new InfoWindow(button, point, -100);
                map.showInfoWindow(infoWindow);
                //Toast.makeText(mContext, stationName, Toast.LENGTH_SHORT).show();
            }
        }
        return false;
    }

    @Override
    public void onSuccess(Object model, int type) {
        switch (type) {
            case TracePresenter.UPLOAD:
                //每次上传成功更新弹窗
                handler.sendEmptyMessage(0x08);
                break;
            case TracePresenter.GET_REACH:
                break;
            case TracePresenter.START_PATROL:
                Log.i("cyc", "START_PATROL---------开始巡河------");
                //开始巡河，将服务器的数据存入本地
                //删除上次遗留的点位
                sqLiteUtils.deleteAllContact();//清除数据库缓存
                if (points != null)
                    points.clear();
                setFollowType();//设置跟随模式
                Task task = (Task) model;
                editor.putString(Constants.TRACE_TASK_ID, task.getPatrolId());
                Toast.makeText(this, "开始巡检", Toast.LENGTH_SHORT).show();
                stateTv.setText("开始巡检");
                Log.i("cyc", "开启服务----TraceService---------开始巡河----");
                startService(new Intent(this, TraceService.class).setAction(TraceService.START_TRACE_SERVICE));

                endLl.setVisibility(View.VISIBLE);
                starLl.setVisibility(View.GONE);
                editor.putBoolean(Constants.IS_TRACE, true);
                editor.putString(Constants.TRACE_STATE, "正在巡检");
                editor.apply();
                break;
            case TracePresenter.IS_TRACE:
                Integer t = (Integer) model;
                Log.i("cyc", "TracePresenter.IS_TRACE---------------t=" + t);
                if (t == 1) {
                    //正在巡河
                    endLl.setVisibility(View.VISIBLE);
                    starLl.setVisibility(View.GONE);
                    stateTv.setText("正在巡检");
                    Log.i("cyc", "开启服务----TraceService---------正在巡检----");
                    startService(new Intent(this, TraceService.class).setAction(TraceService.START_TRACE_SERVICE));
                } else {
                    endLl.setVisibility(View.GONE);
                    starLl.setVisibility(View.VISIBLE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void getReach(List<Reach> objs) {
        reaches.clear();
        reachNames.clear();
        for (int i = 0; i < objs.size(); i++) {
            if (objs.get(i).getReachName() != null) {
                objs.get(i).setR_flag(0);
                reaches.add(objs.get(i));
                reachNames.add(objs.get(i).getReachName());
            }
        }

//        endLl.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                Log.i("cyc","-------------------------------------");
//                mPresenter.getReservoir();
//            }
//        },10000);
        mPresenter.getReservoir();

    }

    @Override
    public void getReservoir(List<Reach> objs) {
        for (int i = 0; i < objs.size(); i++) {
            if (objs.get(i).getReservoirName() != null) {
                objs.get(i).setR_flag(1);
                reaches.add(objs.get(i));
                reachNames.add(objs.get(i).getReservoirName());
            }
        }
        try {
            if (bottomDialog != null) {
                bottomDialog.list.setVisibility(View.VISIBLE);
                bottomDialog.mPb_progress.setVisibility(View.GONE);
                bottomDialog.mAdapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void traceHistory(List<TraceSearch> model) {
        Log.i(TAG, "traceHistory ===> ");
        if (model.size() < 3) {
            Toast.makeText(getApplicationContext(), "描点少于三个", Toast.LENGTH_SHORT).show();
            return;
        }
        setMyLocation(Double.valueOf(model.get(0).getPatrolLatitude()), Double.valueOf(model.get(0).getPatrolLongitude()));
        List<OverlayOptions> overlayOptions = addOverlayPath(mapView, model);
        BitmapDescriptor icon1 = BitmapDescriptorFactory.fromResource(R.drawable.yuandian);
        for (int i = 0; i < model.size(); i++) {
            Log.i(TAG, "traceHistory ===> " + model.get(i).getPatrolLatitude() + "::" + model.get(i).getPatrolLongitude());
            LatLng point = new LatLng(Double.valueOf(model.get(i).getPatrolLatitude()),
                    Double.valueOf(model.get(i).getPatrolLongitude()));
            OverlayOptions option1 = new MarkerOptions()
                    .position(point)
//                    .titleOptions(new TitleOptions()
//                            .text("title" + i))
                    .icon(icon1);
            overlayOptions.add(option1);
        }
        map.addOverlays(overlayOptions);
    }

    @Override
    public void onFailed(String message) {
        allSuccess = false;
        handler.sendEmptyMessage(0x07);
    }


    /**
     * 授予悬浮窗权限
     */
    private void requireFloatViewPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (!Settings.canDrawOverlays(this)) {// 是否具有悬浮窗权限
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 0x01);
            }
        }
    }

    private void requireLocPermission() {
        //Android 6.0判断用户是否授予定位权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//如果 API level 是大于等于 23(Android 6.0) 时
            //判断是否具有权限
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //判断是否需要向用户解释为什么需要申请该权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    Toast.makeText(this, "需要授权位置权限", Toast.LENGTH_SHORT).show();
                }
                //请求权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 0x02);
            }
        }
    }

}
